/************************************************/
/* Build a Dynamic HTML table from JSON results */
/* By: Zachary Hunter                           */
/* On: April 1, 2010                            */
/************************************************/

function createTableView(options) {
  // set optional options.theme parameter
  if (options.theme === undefined) {
    options.theme = ''; //default options.theme
  }

  if (options.enableHeader === undefined) {
    options.enableHeader = true; //default enable headers
  }

  if (options.widthTable === undefined) {
    options.widthTable = ''; //default enable headers
  }

  var isArray = typeof(options.objArray)=='object' && (options.objArray instanceof Array);
  var array = (isArray) ? options.objArray : JSON.parse(options.objArray);

  var classNameTable = (options.theme == "") ? "" : "class=\""+ options.theme +"\"";
  options.widthTable = (options.widthTable == "") ? "" : "width:"+ options.widthTable +";";

  var str = '<table border="0" cellpadding="2" cellspacing="0" style="border-width:0;'+ options.widthTable +'" '+ classNameTable +'>';

  // table head
  if (options.enableHeader) {
    str += '<thead><tr>';
    for (var index in array[0]) {
      str += '<th scope="col">' + index + '</th>';
    }
    str += '</tr></thead>';
  }

  // table body
  str += '<tbody>';
  for (var i = 0; i < array.length; i++) {
    str += (i % 2 == 0) ? '<tr class="alt">' : '<tr>';
    for (var index in array[i]) {
      str += '<td>' + array[i][index] + '</td>';
    }
    str += '</tr>';
  }
  str += '</tbody>'
  str += '</table>';
  return str;
}

function createDetailView(options) {
  // set optional options.theme parameter
  if (options.theme === undefined) {
    options.theme = '';  //default options.theme
  }

  if (options.enableHeader === undefined) {
    options.enableHeader = true; //default enable headers
  }

  if (options.widthTable === undefined) {
    options.widthTable = ''; //default enable headers
  }

  var isArray = typeof(options.objArray)=='object' && (options.objArray instanceof Array);
  var array = (isArray) ? options.objArray : JSON.parse(options.objArray);

  var classNameTable = (options.theme == "") ? "" : "class=\""+ options.theme +"\"";
  var str = '<table border="0" cellpadding="2" cellspacing="0" style="border-width:0;'+ options.widthTable +'" '+ classNameTable +'>';
  str += '<tbody>';


  for (var i = 0; i < array.length; i++) {
    var row = 0;
    for (var index in array[i]) {
      str += (row % 2 == 0) ? '<tr class="alt">' : '<tr>';

      if (options.enableHeader) {
        str += '<th scope="row">' + index + '</th>';
      }

      str += '<td>' + array[i][index] + '</td>';
      str += '</tr>';
      row++;
    }
  }
  str += '</tbody>'
  str += '</table>';
  return str;
}